import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_study/config/ConstString.dart';
import 'package:flutter_study/util/navigator_manager.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';

class WebPage extends StatefulWidget {
  final String url;

  const WebPage({Key key, @required this.url}) : super(key: key);

  @override
  _WebPageState createState() => _WebPageState();
}

class _WebPageState extends State<WebPage> {
  FlutterWebviewPlugin flutterWebviewPlugin = FlutterWebviewPlugin();
  var currentUrl = '';

  @override
  void initState() {
    super.initState();
    flutterWebviewPlugin.onUrlChanged.listen((event) {
      currentUrl = event;
    });
    flutterWebviewPlugin.onStateChanged.listen((event) {
      if (event.type == WebViewState.finishLoad) {
        String js = "javascript:(function() {document.getElementsByClassName(\"share-bar-container\")[0].style.display=\'none\';" +
            "document.getElementsByClassName(\"footer-container j-footer-container\")[0].style.display=\'none\';" +
            "document.getElementsByClassName(\"kyt-promotion-bar-positioner\")[0].style.display=\'none\';" +
            "})()";
        flutterWebviewPlugin.evalJavascript(js);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      routes: {
        "/": (context) {
          return WillPopScope(
              child: WebviewScaffold(
                url: widget.url,
                appBar: _appBar(),
                withZoom: true,
                withJavascript: true,
                hidden: true,
                scrollBar: false,
                initialChild: Container(
                  child: Center(
                    child: CircularProgressIndicator(),
                  ),
                ),
              ),
              onWillPop: _onWillPop);
        },
      }
    );
  }

  _appBar() {
    return AppBar(
      leading: GestureDetector(
        onTap: () {
          if (widget.url == currentUrl || currentUrl.isEmpty) {
            NavigatorManager.back();
          } else {
            flutterWebviewPlugin.goBack();
          }
        },
        child: Icon(
          Icons.arrow_back,
          size: 25,
          color: Colors.black,
        ),
      ),
      title: Text(
        ConstString.news_title,
        style: TextStyle(
            color: Colors.black, fontSize: 20, fontWeight: FontWeight.bold),
      ),
      centerTitle: true,
      backgroundColor: Colors.white,
      elevation: 0.0,
      brightness: Brightness.light,
    );
  }

  Future<bool> _onWillPop() {
    if (widget.url == currentUrl) {
      NavigatorManager.back();
      return Future.value(true);
    } else {
      flutterWebviewPlugin.goBack();
      return Future.value(false);
    }
  }
}
